<template>
  <div class="users">
    <!-- 搜索input button -->
    <div class="search-box">
      <div class="input-con">
        <el-input v-model="input" placeholder="请输入内容" style="width: 300px">
          <template #append>
            <el-button :icon="Search" @click="innitRequest" />
          </template>
        </el-input>
      </div>
      <div class="btn">
        <el-button type="primary" @click="dialogVisible = true"
          >添加用户</el-button
        >
      </div>
    </div>
    <!-- 添加用户（使用dialog对话框） -->
    <el-dialog v-model="dialogVisible" title="添加用户" width="45%">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 初始表格 -->
    <div class="table-cons">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column
          v-for="(user, index) in options"
          :key="index"
          :prop="user.prop"
          :label="user.label"
          :width="user.width"
        >
          <!-- 表格里的状态(switch开关) -->
          <template v-slot="{ row }" v-if="user.prop === 'mg_state'">
            <el-switch v-model="row.mg_state" @change="changeState(row)" />
          </template>
          <!-- 表格里的操作(三个button) -->
          <template #default v-else-if="user.prop === 'actions'">
            <!-- 1编辑 -->
            <el-tooltip
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button type="primary" :icon="Edit" size="small" />
            </el-tooltip>

            <!-- 2删除 -->
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                v-for="user in tableData"
                :key="user.id"
                @click="delUser(user.id)"
              />
            </el-tooltip>
            <!-- 3分配角色 -->
            <el-tooltip
              class="box-item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                :icon="Setting"
                size="small"
                @click="dialog = true"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 3分配角色弹出框 -->
      <div class="assign-roles">
        <el-dialog v-model="dialog" title="分配角色" width="50%">
          <p>当前用户:</p>
          <p>当前角色:</p>
          <el-select v-model="value" class="m-2" placeholder="Select">
            <el-option
              v-for="item in op"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialog = false">取消</el-button>
              <el-button type="primary" @click="dialog = false">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
    <!-- 分页器（用到的组件Pagination） -->
    <el-pagination
      v-model:currentPage="queryForm.pagenum"
      v-model:page-size="queryForm.pagesize"
      :page-sizes="[1, 3, 5, 7]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>
<script setup>
import { getCurrentInstance, ref, reactive } from "vue";
const { $axios } = getCurrentInstance().appContext.config.globalProperties;
import axios from "axios";
import { Search, Edit, Setting, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 1.搜索框input
const input = ref("");

const tableData = ref([]); // 声明tableData为初始表格里的数据

// 2.点击搜索从新获取数据的请求
const queryForm = ref({
  query: "", // 查询参数
  pagenum: 1, // 当前页码
  pagesize: 2, // 每页显示条数
});

// 分页器 总的页数
const total = ref(0);

// 添加用户对话框
const dialogVisible = ref(false);
// 添加用户
const form = reactive({
  username: "",
  password: "",
  email: "",
  mobile: "",
});

//http://106.12.150.223:8090/api/private/v1/users?query=&pagenum=1&pagesize=2
const innitRequest = async () => {
  await axios
    .get(
      `/api/users?query=${input.value}&pagenum=${queryForm.value.pagenum}&pagesize=${queryForm.value.pagesize}`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
      }
    )
    .then((data) => {
      // console.log(data);
      tableData.value = data.data.data.users;
      total.value = data.data.data.total; // 总页码
    });
};
innitRequest();

// 分页器 每页显示的条数
const handleSizeChange = (pageSize) => {
  // console.log(pageSize);
  // queryForm.value.pagenum = 1;
  // queryForm.value.pagesize = pageSize;
  innitRequest();
};
// 分页器 当前显示的页码
const handleCurrentChange = (pageNum) => {
  // queryForm.value.pagenum = pageNum;
  innitRequest();
};

// 表格里的用户状态请求(开关)
const state = async (uId, type) => {
  await axios
    .put(`/api/users/${uId}/state/${type}`, {
      // headers: {
      //   Authorization: localStorage.getItem("token"),
      // },
    })
    .then((res) => {
      // console.log(res);
      type = Boolean(res.data.data.mg_state);
    });
};
const changeState = async (info) => {
  // console.log(info); // 获取当前点击状态的对象
  await state(info.id, info.mg_state);
  ElMessage({
    message: "设置状态更新成功",
    type: "success",
  });
};
// 表头添加用户
const ruleFormRef = ref(null);
// 表头添加用户的表单校验(在页面上prop一定声明一下才有星星和提示)
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入正确的邮箱",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
  ],
});
// 添加用户的请求
const adds = ref(2);
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      axios
        .post(
          "/api/users",
          {
            username: form.username,
            password: form.password,
            email: form.email,
            mobile: form.mobile,
          },
          {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          }
        )
        .then((data) => {
          // console.log(data);
          adds.value = data.data.meta.status;
          dialogVisible.value = false;
          resetForm(formEl);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 编辑用户

// 分配角色
const dialog = ref(false);
const value = ref("");
const op = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
  {
    value: "Option3",
    label: "Option3",
  },
  {
    value: "Option4",
    label: "Option4",
  },
  {
    value: "Option5",
    label: "Option5",
  },
];

//表格里的删除按钮，删除单个用户
const delUser = (id) => {
  // console.log(id);
  axios
    .delete(`/api/users/${id}`, {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
    })
    .then((data) => {
      // console.log(data);
      // console.log(data.data.meta.status);
      if (data.data.meta.status == 200) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }
      innitRequest(); // 从新刷新
    });
};
// 表格中表头渲染的初始数据
const options = ref([
  {
    prop: "id",
    label: "用户id",
  },
  {
    prop: "username",
    label: "用户名",
  },
  {
    prop: "email",
    label: "邮箱",
  },
  {
    prop: "mobile",
    label: "电话",
  },
  {
    prop: "role_name",
    label: "角色",
  },
  {
    prop: "mg_state",
    label: "状态",
  },
  {
    prop: "actions",
    label: "操作",
    width: 200, // 渲染的时候button按钮叠加了，所以在这给一个宽度，在template使用(:width="user.width")
  },
]);
</script>

<style lang="less">
.users {
  .search-box {
    display: flex;
    .input-con {
    }
    .btn {
      margin-left: 20px;
    }
  }
  /* 表格 */
  .table-cons {
    margin-top: 10px;
  }
}
</style>
